package org.example.domain.strategy.service.armory;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.model.entity.StrategyRuleEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.types.common.Constants;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.*;

@Service
@Slf4j
public class StrategyArmoryDispatch implements IStrategyArmory ,IStrategyDispatch{

    @Resource
    private IStrategyRepository repository;
    @Override
    public Boolean assembleLotteryStrategy(Long strategyId) {
        //查询策略配置
        List<StrategyAwardEntity> strategyAwardEntities =repository.queryStrategyAwardList(strategyId);
        //缓存奖品库存【用于decr扣减使用】
        for (StrategyAwardEntity strategyAward :strategyAwardEntities){
            Integer awardId=strategyAward.getAwardId();
            Integer awardCount=strategyAward.getAwardCount();
            cacheStrategyAwardCount(strategyId,awardId,awardCount);
        }
        //默认装配配置-抽奖概率
        assembleLotteryStrategy(String.valueOf(strategyId),strategyAwardEntities);
        //查出来null
        StrategyEntity strategyEntity= repository.queryStrategyEntityByStrategyId(strategyId);

        //处理100001策略--ruleWeight
        String ruleWeight = strategyEntity.getRuleWeight();
        if(null==ruleWeight)return true;
        StrategyRuleEntity strategyRuleEntity=repository.queryStrategyRule( strategyId, ruleWeight );

        if(null==strategyRuleEntity){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }

        Map<String, List<Integer>> ruleWeightValuesMap = strategyRuleEntity.getRuleWeightValues();
        Set<String> keys = ruleWeightValuesMap.keySet();
        for (String key: keys){
            List<Integer> ruleWeightValues  = ruleWeightValuesMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);//复制一份
            strategyAwardEntitiesClone.removeIf(entity->!ruleWeightValues.contains(entity.getAwardId()));//把不属于的删掉
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key),strategyAwardEntitiesClone);
        }
        return true;
    }
    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;//Constants.UNDERLINE表示"_"
        repository.cacheStrategyAwardCount(cacheKey,awardCount);
    }



    /**
     * 计算过程：
     * 1.找到最小的概率值，比如0.1,0.02,0.003
     *2.找到0.003，计算出百分比千分比--1000
     * 3.那么【概率*1000】表示0.1,0.02.0.003对应的奖品个数为100,20,3,总共123个
     * 4.生成的123个数值充当奖品池用于抽奖
     */
    private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        // 1. 获取最小概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        // 2. 循环计算找到概率范围值
        BigDecimal rateRange = BigDecimal.valueOf(convert(minAwardRate.doubleValue()));

        // 3. 生成策略奖品概率查找表「这里指需要在list集合中，存放上对应的奖品占位即可，占位越多等于概率越高」
        List<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            // 计算出每个概率值需要存放到查找表的数量，循环填充
            for (int i = 0; i < rateRange.multiply(awardRate).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }

        // 4. 对存储的奖品进行乱序操作
        Collections.shuffle(strategyAwardSearchRateTables);

        // 5. 生成出Map集合，key值，对应的就是后续的概率值。通过概率来获得对应的奖品ID
        Map<Integer, Integer> shuffleStrategyAwardSearchRateTable = new LinkedHashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
        }

        // 6. 存放到 Redis
        repository.storeStrategyAwardSearchRateTables(key, shuffleStrategyAwardSearchRateTable.size(), shuffleStrategyAwardSearchRateTable);
    }

    /**
     * 转换计算，只根据小数位来计算。如【0.01返回100】、【0.009返回1000】、【0.0018返回10000】
     */
    private double convert(double min) {
        double current = min;
        double max = 1;
        while (current < 1) {
            current = current * 10;
            max = max * 10;
        }
        return max;
    }





    @Override
    public Integer getRandomAwardId(Long strategyId) {
        //获取范围
        int rateRage=repository.getRateRange(strategyId);
        //根据生成的随机值进行抽奖
        Integer awardId=repository.getStrategyAwardAssemble(String.valueOf(strategyId),new SecureRandom().nextInt(rateRage));
        return  awardId;
    }

    @Override
    public Boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId=repository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key=String.valueOf(strategyId).concat("_").concat(ruleWeightValue);//10001_4000:102,103,104,105
        int rateRage=repository.getRateRange(key);//概率范围:总和/min
        return repository.getStrategyAwardAssemble(key,new SecureRandom().nextInt(rateRage));
    }


    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId,Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;//Constants.UNDERLINE表示"_"
        return repository.subtractionAwardStock(cacheKey);
    }
}
